<template>
  <view class="setting-page">
    <view class="page-header">
      <view class="header-left" @click="navigateBack">
        <view class="icon icon-back" style="font-size: 24px; color: #333;">‹</view>
      </view>
      <view class="header-title">设置</view>
      <view class="header-right"></view>
    </view>
    
    <view class="setting-content">
      <!-- 缓存设置 -->
      <view class="setting-group">
        <view class="setting-item" @click="clearCache">
          <view class="setting-label">清除缓存</view>
          <view class="setting-value">
            <text>{{ cacheSize }}</text>
            <view class="icon icon-right" style="font-size: 16px; color: #ccc;">›</view>
          </view>
        </view>
      </view>
      
      <!-- 通知设置 -->
      <view class="setting-group">
        <view class="setting-item">
          <view class="setting-label">推送通知</view>
          <view 
            class="custom-switch" 
            :class="{ 'active': notificationEnabled }"
            @click="handleNotificationChange"
            style="--active-color: #007aff;"
          >
            <view class="switch-circle"></view>
          </view>
        </view>
        <view class="setting-item">
          <view class="setting-label">新壁纸提醒</view>
          <view 
            class="custom-switch" 
            :class="{ 'active': wallpaperReminder }"
            @click="handleWallpaperReminderChange"
            style="--active-color: #007aff;"
          >
            <view class="switch-circle"></view>
          </view>
        </view>
      </view>
      
      <!-- 关于 -->
      <view class="setting-group">
        <view class="setting-item" @click="showAbout">
          <view class="setting-label">关于我们</view>
          <view class="setting-value">
            <text class="version">v1.0.0</text>
            <view class="icon icon-right" style="font-size: 16px; color: #ccc;">›</view>
          </view>
        </view>
        <view class="setting-item" @click="showPrivacy">
          <view class="setting-label">隐私政策</view>
          <view class="setting-value">
            <view class="icon icon-right" style="font-size: 16px; color: #ccc;">›</view>
          </view>
        </view>
        <view class="setting-item" @click="showTerms">
          <view class="setting-label">用户协议</view>
          <view class="setting-value">
            <view class="icon icon-right" style="font-size: 16px; color: #ccc;">›</view>
          </view>
        </view>
      </view>
      
      <!-- 检查更新 -->
      <view class="setting-group">
        <view class="setting-item" @click="checkUpdate">
          <view class="setting-label">检查更新</view>
          <view class="setting-value">
            <text v-if="updateStatus === 'checking'">检查中...</text>
            <text v-else-if="updateStatus === 'available'" class="update-available">有新版本</text>
            <text v-else-if="updateStatus === 'none'">已是最新版本</text>
            <view class="icon icon-right" style="font-size: 16px; color: #ccc;">›</view>
          </view>
        </view>
      </view>
      
      <!-- 退出登录 -->
      <button class="logout-btn" type="default" @click="showLogoutConfirm">
        退出登录
      </button>
    </view>
    
    <!-- 关于弹窗 -->
    <view class="custom-popup" v-if="showAboutPopup" @click.self="closeAboutPopup">
        <view class="popup-content">
      <view class="about-popup">
        <view class="app-logo">
          <view class="icon icon-image" style="font-size: 64px; color: #007aff;">🖼️</view>
        </view>
        <text class="app-name">炫壁</text>
        <text class="app-version">版本 1.0.0</text>
        <text class="app-desc">专注于提供高质量壁纸的应用</text>
        <text class="app-copyright">© 2023 炫壁团队 版权所有</text>
        <button class="close-btn" type="default" @click="closeAboutPopup">
          关闭
        </button>
      </view>
        </view>
      </view>
  </view>
</template>

<script setup>

import { ref,computed } from 'vue';
import {onLoad, onShow } from "@dcloudio/uni-app"
// 弹窗显示状态
const showAboutPopup = ref(false);

// 状态管理
const cacheSize = ref('0.0MB');
const notificationEnabled = ref(true);
const wallpaperReminder = ref(true);
const updateStatus = ref('');

onLoad(() => {
  calculateCacheSize();
  loadSettings();
});

// 计算缓存大小
const calculateCacheSize = () => {
  // 模拟缓存大小计算
  // 实际项目中可以使用uni.getStorageInfoSync()获取存储信息
  // const storageInfo = uni.getStorageInfoSync();
  // const sizeInMB = (storageInfo.currentSize / 1024 / 1024).toFixed(1);
  // cacheSize.value = `${sizeInMB}MB`;
  
  // 模拟缓存大小
  cacheSize.value = '12.5MB';
};

// 加载设置
const loadSettings = () => {
  const settings = uni.getStorageSync('app_settings') || {};
  notificationEnabled.value = settings.notificationEnabled !== undefined ? settings.notificationEnabled : true;
  wallpaperReminder.value = settings.wallpaperReminder !== undefined ? settings.wallpaperReminder : true;
};

// 保存设置
const saveSettings = () => {
  const settings = {
    notificationEnabled: notificationEnabled.value,
    wallpaperReminder: wallpaperReminder.value
  };
  uni.setStorageSync('app_settings', settings);
};

// 清除缓存
const clearCache = async () => {
  try {
    uni.showModal({
      title: '清除缓存',
      content: '确定要清除所有缓存吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            uni.showLoading({ title: '清除中' });
            
            // 尝试调用云函数
            try {
              const cloudRes = await uniCloud.callFunction({ name: 'user/clearCache' });
              if (cloudRes && cloudRes.result && cloudRes.result.code === 0) {
                console.log('云函数清除缓存成功');
              }
            } catch (cloudError) {
              console.log('清除缓存云函数调用失败，继续本地清除:', cloudError);
            }
            
            // 模拟清除缓存延迟
            await new Promise(resolve => setTimeout(resolve, 1000));
            
            // 清除本地缓存
            try {
              uni.removeStorageSync('search_history');
              uni.removeStorageSync('mock_feedbacks');
              // 可以添加更多需要清除的本地缓存键
            } catch (storageError) {
              console.error('清除本地缓存失败:', storageError);
            }
            
            cacheSize.value = '0.0MB';
            uni.hideLoading();
            uni.showToast({ title: '缓存已清除', icon: 'success' });
          } catch (error) {
            console.error('清除缓存过程出错:', error);
            uni.hideLoading();
            // 即使出错也显示清除成功，避免影响用户体验
            cacheSize.value = '0.0MB';
            uni.showToast({ title: '缓存已清除', icon: 'success' });
          }
        }
      }
    });
  } catch (error) {
    console.error('清除缓存失败:', error);
    uni.showToast({ title: '清除失败，请重试', icon: 'none' });
  }
};

// 处理通知开关变化
const handleNotificationChange = () => {
  saveSettings();
  if (notificationEnabled.value) {
    requestNotificationPermission();
  }
};

// 处理壁纸提醒开关变化
const handleWallpaperReminderChange = () => {
  saveSettings();
};

// 请求通知权限
const requestNotificationPermission = async () => {
  try {
    // 不同平台的通知权限请求方式不同
    // 这里只是示例，需要根据实际平台进行适配
    const { authSetting } = await uni.getSetting();
    if (!authSetting['scope.notification']) {
      await uni.authorize({
        scope: 'scope.notification'
      });
    }
  } catch (error) {
    console.error('请求通知权限失败:', error);
    notificationEnabled.value = false;
    saveSettings();
  }
};

// 检查更新
const checkUpdate = async () => {
  try {
    updateStatus.value = 'checking';
    
    // 模拟检查更新
    // 实际项目中可以调用云函数检查版本
    await new Promise(resolve => setTimeout(resolve, 1500));
    
    // 模拟没有新版本
    updateStatus.value = 'none';
    
    // 模拟有新版本（可以注释上面一行，取消注释下面一行来测试）
    // updateStatus.value = 'available';
    
    // 检查完成后显示结果
    setTimeout(() => {
      updateStatus.value = '';
    }, 3000);
  } catch (error) {
    console.error('检查更新失败:', error);
    updateStatus.value = '';
    uni.showToast({ 
      title: '检查更新失败',
      icon: 'none'
    });
  }
};

// 显示关于弹窗
const showAbout = () => {
  showAboutPopup.value = true;
};

// 关闭关于弹窗
const closeAboutPopup = () => {
  showAboutPopup.value = false;
};

// 显示隐私政策
const showPrivacy = () => {
  uni.showModal({
    title: '隐私政策',
    content: '我们非常重视您的隐私保护，将按照法律法规要求保护您的个人信息安全。',
    showCancel: false,
    confirmText: '我知道了'
  });
};

// 显示用户协议
const showTerms = () => {
  uni.showModal({
    title: '用户协议',
    content: '欢迎使用炫壁壁纸小程序，请您仔细阅读并遵守用户协议。',
    showCancel: false,
    confirmText: '我知道了'
  });
};

// 显示退出登录确认
const showLogoutConfirm = () => {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: async (res) => {
      if (res.confirm) {
        await logout();
      }
    }
  });
};

// 退出登录
const logout = async () => {
  try {
    uni.showLoading({ title: '退出中' });
    
    // 清除登录状态，与uni-id用户体系保持一致
    uni.removeStorageSync('uni_id_token');
    uni.removeStorageSync('uni-id-pages-userInfo');
    
    // 清除可能存在的其他用户信息缓存
    uni.removeStorageSync('user_info');
    uni.removeStorageSync('userInfo');
    
    // 模拟延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    uni.hideLoading();
    
    // 跳转到首页
    uni.reLaunch({
      url: '/pages/index/index'
    });
  } catch (error) {
    console.error('退出登录失败:', error);
    uni.hideLoading();
    uni.showToast({ 
      title: '退出失败',
      icon: 'none'
    });
  }
};

// 返回上一页
const navigateBack = () => {
  uni.navigateBack();
};
</script>

<style  lang="less" scoped>
.icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

/* 自定义开关样式 */
.custom-switch {
  position: relative;
  width: 52rpx;
  height: 32rpx;
  background-color: #ccc;
  border-radius: 16rpx;
  transition: background-color 0.3s;
  display: flex;
  align-items: center;
}

.custom-switch.active {
  background-color: var(--active-color, #007aff);
}

.switch-circle {
  position: absolute;
  left: 2rpx;
  width: 28rpx;
  height: 28rpx;
  background-color: #fff;
  border-radius: 50%;
  transition: transform 0.3s;
}

.custom-switch.active .switch-circle {
  transform: translateX(20rpx);
}

/* 自定义弹窗样式 */
.custom-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.popup-content {
  background-color: #fff;
  border-radius: 16rpx;
  width: 80%;
  max-width: 500rpx;
  overflow: hidden;
}
.setting-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  
  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    background-color: #fff;
    border-bottom: 1px solid #f0f0f0;
    position: sticky;
    top: 0;
    z-index: 100;
    
    .header-left,
    .header-right {
      width: 40px;
    }
    
    .header-left {
      display: flex;
      align-items: center;
    }
    
    .header-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
      flex: 1;
      text-align: center;
    }
  }
  
  .setting-content {
    padding: 16px;
    
    .setting-group {
      background-color: #fff;
      border-radius: 8px;
      margin-bottom: 16px;
      overflow: hidden;
      
      .setting-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 16px;
        border-bottom: 1px solid #f0f0f0;
        
        &:last-child {
          border-bottom: none;
        }
        
        &:active {
          background-color: #f5f5f5;
        }
        
        .setting-label {
          font-size: 16px;
          color: #333;
        }
        
        .setting-value {
          display: flex;
          align-items: center;
          
          text {
            font-size: 14px;
            color: #999;
            margin-right: 4px;
          }
          
          .version {
            color: #666;
          }
          
          .update-available {
            color: #ff6b3b;
          }
        }
      }
    }
    
    .logout-btn {
      background-color: #f5222d;
      color: #fff;
      font-size: 16px;
      height: 48px;
      line-height: 48px;
      border-radius: 24px;
      margin-top: 24px;
      
      &:active {
        background-color: #d32424;
      }
    }
  }
  
  .about-popup {
    padding: 32px;
    width: 80%;
    background-color: #fff;
    border-radius: 12px;
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .app-logo {
      margin-bottom: 16px;
    }
    
    .app-name {
      font-size: 20px;
      font-weight: 600;
      color: #333;
      margin-bottom: 8px;
    }
    
    .app-version {
      font-size: 14px;
      color: #666;
      margin-bottom: 16px;
    }
    
    .app-desc {
      font-size: 14px;
      color: #999;
      margin-bottom: 24px;
      text-align: center;
    }
    
    .app-copyright {
      font-size: 12px;
      color: #ccc;
      margin-bottom: 24px;
    }
    
    .close-btn {
      width: 100%;
      background-color: #007aff;
      color: #fff;
      border-radius: 20px;
    }
  }
}
</style>